<template>
  <div class="container">
    <el-card class="app-container">
      <div slot="header" class="clearfix">
        <span>角色管理</span>
      </div>
      <!-- 搜索区域 -->
      <el-form ref="searchForm" label-width="120px" :model="search" class="filter-form">
        <el-row :gutter="5">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="角色名称:">
              <el-input v-model="search.search" size="small" placeholder="请输入角色名称" />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="角色状态:">
              <el-select v-model="search.status" size="small" placeholder="请选择">
                <el-option label="启用" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="12" style="display: flex; justify-content: flex-end;">
            <el-form-item>
              <el-button type="primary" size="medium" @click="handleSearch">查询</el-button>
              <el-button size="medium" @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 数据表格 -->
      <div style="width: 100%;">
        <div style="margin-bottom: 15px; display: flex; justify-content: flex-start;">
          <el-button size="medium" type="primary" @click="addBtn">新增</el-button>
        </div>
        <div>
          <el-table
            ref="tableRef"
            :data="tableData"
            border
            style="width: 100%"
          >
            <el-table-column type="index" width="80" align="center" />
            <!-- <el-table-column prop="no" label="角色编号" align="center" /> -->
            <el-table-column prop="name" label="角色名称" align="center" />
            <el-table-column prop="name" label="角色顺序(后续)" align="center" />
            <el-table-column prop="activationTime" label="状态" align="center">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.status"
                  :active-value="1"
                  :inactive-value="0"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  @change="handleStatusChange(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="180"
              fixed="right"
              align="center"
            >
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="handleEdit(scope.row)">修改</el-button>
                <!-- <el-button type="text" size="mini" @click="handleDel(scope.row)">删除</el-button> -->
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增 -->
    <el-dialog :close-on-click-modal="false" :title="`${addOrEditFlag === 'add' ? '新增角色' : '编辑角色'}`" :visible.sync="dialogVisible" width="25%" class="add" @close="dialogClose">
      <div style="height: 100%; display: flex; flex-direction: column; overflow-y: auto; padding: 0 20px 0 0;">
        <el-form ref="addRef" :model="form" :rules="formRules" label-width="120px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="角色名称" prop="name">
                <el-input v-model="form.name" size="small" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="角色顺序(后续)" prop="name1">
                <el-input-number v-model="form.name1" size="small" :min="0" :max="10000" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio :label="1">启用</el-radio>
                  <el-radio :label="0">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="菜单权限" prop="role_permissions">
                <div style="margin-left: 8px;">
                  <el-checkbox v-model="checkedZ" @change="checkChangeZ">展开/折叠</el-checkbox>
                  <el-checkbox v-model="checkedX" @change="checkChangeX">全选/全不选</el-checkbox>
                </div>
                <el-tree
                  ref="tree"
                  :data="treeData"
                  show-checkbox
                  node-key="id"
                  :props="defaultProps"
                  :default-expanded-keys="defaultExpandedKeys"
                  @check="handleCheckChange"
                />
              </el-form-item>
            </el-col>
            <el-col style="margin-top: 10px;" :span="24">
              <el-form-item label="备注" prop="description">
                <el-input v-model="form.description" type="textarea" :rows="4" size="small" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">返回</el-button>
        <el-button size="small" type="primary" @click="submitForm">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, addOrEditRole, rolePermission, roleStatus, roleDel } from '@/api/role'
import { menuTree } from '@/api/menu'

export default {
  data() {
    return {
      allList: [],
      checkedZ: false,
      checkedX: false,
      treeData: [],
      addOrEditFlag: 'add',
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      dialogVisible: false,
      formRules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选中状态', trigger: 'change' }
        ],
        role_permissions: [
          { required: true, message: '请选择菜单权限', trigger: 'change' }
        ]
      },
      form: {
        id: null,
        name: '',
        name1: '',
        status: null,
        role_permissions: [],
        description: ''
      },
      search: {
        search: '',
        status: ''
      },
      defaultExpandedKeys: [],
      tableData: [],
      pagination: {
        page: 1,
        pageSize: 10,
        total: 0
      }
    }
  },
  created() {
    this.fetchData()

    this.meunTree()
  },
  methods: {
    async handleStatusChange(row) {
      const obj = {
        id: row.id
      }
      await roleStatus(obj)
    },
    async meunTree() {
      const res = await menuTree()
      this.allList = res
      this.treeData = this.buildMenuTree(res)
    },
    buildMenuTree(flatData, parentId = '0') {
      return flatData
        .filter(item => item.parent_id === parentId)
        .map(item => ({
          ...item,
          children: this.buildMenuTree(flatData, item.id)
        }))
    },
    handleCheckChange(node, data) {
      // 全选/全不选逻辑
      const totalNodes = this.flattenTree(this.treeData).length
      // 自动选中父节点
      const parent = this.$refs.tree.getNode(node).parent
      if (parent && !parent.checked) {
        this.$refs.tree.setChecked(parent.key, true)
      }
      // 检查是否所有子节点都未选中
      if (parent) {
        const allChildrenUnchecked = parent.childNodes.every(child => !child.checked)
        if (allChildrenUnchecked) {
          this.$refs.tree.setChecked(parent.key, false)
        }
      }
      // 处理节点点击事件
      const checkedKeys = this.$refs.tree.getCheckedKeys()
      this.form.role_permissions = checkedKeys
      console.log(checkedKeys)
      this.$refs.addRef.validateField('role_permissions')

      this.checkedX = checkedKeys.length === totalNodes
    },
    flattenTree(nodes) {
      let result = []
      nodes.forEach(node => {
        result.push(node)
        if (node.children && node.children.length) {
          result = result.concat(this.flattenTree(node.children))
        }
      })
      return result
    },
    checkChangeZ(val) {
      if (val) {
        // 展开全部节点
        this.$refs.tree.setCurrentKey(null)
        Object.values(this.$refs.tree.store.nodesMap).forEach(node => {
          node.expanded = true
        })
      } else {
        // 折叠全部节点
        Object.values(this.$refs.tree.store.nodesMap).forEach(node => {
          node.expanded = false
        })
      }
    },
    checkChangeX(val) {
      if (val) {
        const totalNodes = this.flattenTree(this.treeData)
        const allKeys = totalNodes.map(item => item.id)
        console.log(allKeys)

        this.$refs.tree.setCheckedKeys(allKeys)
        this.form.role_permissions = allKeys
      } else {
        this.$refs.tree.setCheckedKeys([])
        this.form.role_permissions = []
      }
    },
    dialogClose() {
      this.$refs.addRef.resetFields()
      this.$refs.tree.setCheckedKeys([])
      this.form = {
        id: null,
        name: '',
        name1: '',
        status: null,
        role_permissions: [],
        description: ''
      }
      this.checkedZ = false
      this.checkedX = false
    },
    addBtn() {
      this.addOrEditFlag = 'add'
      this.dialogVisible = true
    },
    submitForm() {
      this.$refs.addRef.validate(async(valid) => {
        if (valid) {
          const str = this.form.role_permissions.join(',')
          const obj = {
            id: this.form.id ? this.form.id : null,
            name: this.form.name,
            name1: this.form.name1,
            status: this.form.status,
            role_permissions: str,
            description: this.form.description
          }
          await addOrEditRole(obj)
          this.handleSearch()
          this.$message.success('提交成功')
          this.dialogVisible = false
        } else {
          return false
        }
      })
    },
    handleDel(row) {
      this.$confirm('确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await roleDel({
          id: row.id
        })
        this.fetchData()
        this.$message.success('删除成功')
      }).catch(() => {
        // this.$message.info('已取消删除')
      })
    },
    async handleEdit(row) {
      this.dialogVisible = true

      // 接口调用获取权限
      const res = await rolePermission({
        id: row.id
      })
      this.$nextTick(() => {
        // 设置选中状态
        this.$refs.tree.setCheckedKeys(res || [])
        this.defaultExpandedKeys = res || []
      })

      this.form = {
        id: row.id,
        name: row.name,
        name1: row.name1,
        status: row.status,
        role_permissions: res,
        description: row.description
      }
      this.addOrEditFlag = 'edit'
    },
    handleSearch() {
      this.pagination.page = 1
      this.fetchData()
    },
    resetSearch() {
      this.search = {
        search: '',
        status: ''
      }
      this.handleSearch()
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.pagination.page = val
      this.fetchData()
    },
    async fetchData() {
      const queryParams = {
        pageSize: this.pagination.pageSize,
        page: this.pagination.page,
        status: this.search.status,
        search: this.search.search
      }
      const res = await getRoleList(queryParams)
      this.tableData = res.list
      this.pagination.total = res.total
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .el-radio__original {
  display: none !important;
}

::v-deep .el-radio:focus:not(.is-focus):not(:active):not(.is-disabled)
  .el-radio__inner {
  box-shadow: none !important;
}
.filter-form {
  padding: 16px;
  padding-bottom: 0;
  margin-bottom: 6px;
  .el-select {
    width: 100%;
  }
}
.el-select {
  width: 100%;
}
.el-form-item {
  margin-bottom: 15px;
}
.filter-container {
  padding: 16px;
  margin-bottom: 6px;
}
.filter-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}
.filter-item {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 200px;
}
.filter-label {
  margin-right: 8px;
  color: #606266;
  white-space: nowrap;
}
.filter-actions {
  margin-left: auto;
}
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}
// popup内部样式
.section-title {
  margin: 16px 0 12px 0;
  font-size: 15px;
  color: #303133;
  font-weight: 600;
}
.info-row {
  display: flex;
  flex-wrap: wrap;
}
.info-item {
  flex: 0 0 33.33%;
  padding: 8px 0;
  display: flex;
  align-items: center;
}
.info-label {
  flex-shrink: 0;
  display: inline-block;
  width: 100px;
  text-align: right;
  color: #909399;
  margin-right: 8px;
}
.info-value {
  color: #606266;
}
.add {
  ::v-deep .el-dialog__body{
    height: 50vh;
    overflow: hidden;
  }
}
.edit {
  ::v-deep .el-dialog__body {
    height: 50vh;
    overflow: hidden;
  }
  ::v-deep .el-input__inner {
    border-radius: 5px;
  }
  .detail-container {
    height: 100%;
    display: flex;
    flex-direction: column;
  }
  .el-table {
    flex: 1;
  }
}
</style>
